package com.v1.video.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 请求参数签名工具类
 * 
 */
public class ParamSignUtil {
	
	public static final String TAG = "ParamSignUtil";

	public static String splitJointParam(HashMap<String, String> signMap) {
		String secret_key = "v1.cn#";
		HashMap SignHashMap = ParamSignUtil.sign(signMap, secret_key);
		String sign = (String) SignHashMap.get("appSign");
		// 获取参数签名字符串
		Logger.i(TAG,"sign:" + sign);
		// 添加签名参数
		signMap.put("s", sign);
		// 获取参数拼接请求url地址
		return getParams("get", signMap);
	}

	public static HashMap<String, String> sign(Map<String, String> paramValues,
			String secret) {
		return sign(paramValues, null, secret);
	}

	/**
	 * @param paramValues
	 * @param ignoreParamNames
	 * @param secret
	 * @return
	 */
	public static HashMap<String, String> sign(Map<String, String> paramValues,
			List<String> ignoreParamNames, String secret) {
		try {
			HashMap<String, String> signMap = new HashMap<String, String>();
			StringBuilder sb = new StringBuilder();
			List<String> paramNames = new ArrayList<String>(paramValues.size());
			paramNames.addAll(paramValues.keySet());
			if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
				for (String ignoreParamName : ignoreParamNames) {
					paramNames.remove(ignoreParamName);
				}
			}
			Collections.sort(paramNames);
			sb.append(secret);
			for (String paramName : paramNames) {
				sb.append(paramName).append(paramValues.get(paramName));
			}
			sb.append(secret);
			byte[] md5Digest = getMD5Digest(sb.toString());
			String sign = byte2hex(md5Digest);
			signMap.put("appParam", sb.toString());
			signMap.put("appSign", sign);
			return signMap;
		} catch (IOException e) {
			throw new RuntimeException("加密签名计算错误", e);
		}

	}

	public static String utf8Encoding(String value, String sourceCharsetName) {
		try {
			return new String(value.getBytes(sourceCharsetName), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException(e);
		}
	}

	private static byte[] getSHA1Digest(String data) throws IOException {
		byte[] bytes = null;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			bytes = md.digest(data.getBytes("UTF-8"));
		} catch (GeneralSecurityException gse) {
			throw new IOException(gse);
		}
		return bytes;
	}

	private static byte[] getMD5Digest(String data) throws IOException {
		byte[] bytes = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			bytes = md.digest(data.getBytes("UTF-8"));
		} catch (GeneralSecurityException gse) {
			throw new IOException(gse);
		}
		return bytes;
	}

	private static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			// sign.append(hex.toUpperCase());
			sign.append(hex.toLowerCase());
		}
		return sign.toString();
	}

	/**
	 * 得到参数列表字符串
	 * 
	 * @param method
	 *            请求类型 get or post
	 * @param paramValues
	 *            参数map对象
	 * @return 参数列表字符串
	 */
	public static String getParams(String method,
			Map<String, String> paramValues) {
		String params = "";
		Set<String> key = paramValues.keySet();
		String beginLetter = "";
		if (method.equalsIgnoreCase("get")) {
			beginLetter = "?";
		}

		for (Iterator<String> it = key.iterator(); it.hasNext();) {
			String s = (String) it.next();
			if (params.equals("")) {
				params += beginLetter + s + "=" + paramValues.get(s);
			} else {
				params += "&" + s + "=" + paramValues.get(s);
			}
		}
		return params;
	}

	/**
	 * 得到参数列表字符串
	 * 
	 * @param method
	 *            请求类型 get or post
	 * @param paramValues
	 *            参数map对象
	 * @return 参数列表字符串
	 */
	public static String getParamsWithSign(String secret_key,
			Map<String, String> signMap) {
		String url = "";
		HashMap SignHashMap = ParamSignUtil.sign(signMap, secret_key);
		String sign = (String) SignHashMap.get("appSign");
		signMap.put("s", sign);
		// System.out.println("get params：：：："+getParams("get",signMap));
		url = getParams("get", signMap);
		// System.out.println("url：：：："+url);
		return url;
	}

}
